class RouteInstance < ActiveRecord::Base

  belongs_to :courier
  
  belongs_to :instantiated_by, :class_name => 'User'
  
  belongs_to :route
  has_many :stop_instances, :dependent => :destroy

  accepts_nested_attributes_for :stop_instances
  
  after_update :save_stop_instances
  validates_associated :stop_instances
  
  def new_stop_instance_attributes=(stop_instance_attributes)
    stop_instance_attributes.each { |attributes|
	  stop_instances.build(attributes)
	}
  end
  
  def existing_stop_instance_attributes=(stop_instance_attributes)
    stop_instances.reject(&:new_record?).each do |stop_instance|
	  attributes = stop_instance_attributes[stop_instance.id.to_s]
	  if attributes
	    stop_instance.attributes = attributes
	  else
	    stop_instances.delete(stop_instance)
	  end
	end
  end
  
  def save_stop_instances
    stop_instances.each do |stop_instance|
	  stop_instance.save(false)
	end
  end
end
